/**
 * 
 */
package com.p2p.front.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.mail.EmailAttachment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import com.itextpdf.text.DocumentException;
import com.p2p.base.annotation.LoginNeedless;
import com.p2p.base.exception.BizException;
import com.p2p.base.model.Money;
import com.p2p.base.service.ProducerService;
import com.p2p.base.util.mail.SendCloudMail;
import com.p2p.front.dal.model.LoanInfo;
import com.p2p.front.dal.model.LoanVariation;
import com.p2p.front.dal.model.TenderReturn;
import com.p2p.front.service.FinanceService;
import com.p2p.front.service.LoanVariationService;
import com.p2p.front.service.SysConfigService;
import com.p2p.front.task.LoanTimeOpenTask;
import com.p2p.front.task.LoanTimeOutTask;
import com.p2p.front.task.RealTimeFinance;
import com.p2p.front.task.RepayTask;
import com.p2p.front.tender.FlowLoanTender;
import com.p2p.front.tender.NormalLoanTender;
import com.p2p.front.util.PdfDownload;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @author ruiqi
 *
 */
@LoginNeedless
@RequestMapping("/test")
@Controller
public class TestController {
	protected final Logger logger = LoggerFactory
			.getLogger(TestController.class);

	@Resource
	private ProducerService producerService;

	@Resource
	private Destination tenderReturntopicDestination;

	@Resource
	private LoanVariationService loanVariationService;

	@Resource
	private FlowLoanTender flowLoanTender;

	@Resource
	private NormalLoanTender normalLoanTender;

	@Resource
	private LoanTimeOutTask loanTimeOutTask;

	@Resource
	private LoanTimeOpenTask loanTimeOpenTask;

	@Resource
	private RepayTask repayTask;

	@Resource
	private RealTimeFinance realTimeFinance;

	@Resource
	private FinanceService financeService;

	@Resource
	private FreeMarkerConfig freemarkerConfig;

	@Resource
	private SysConfigService sysConfigService;

	@RequestMapping("/sendTenderReturnTest")
	public void testSendTenderReturnJMSMessage() {
		TenderReturn tr = new TenderReturn();
		tr.setId(12345L);
		tr.setAmount(new Money(1, 1));
		producerService.sendMessage(tenderReturntopicDestination, tr);
	}

	@RequestMapping("/loanExpired")
	public void testLoanExpired(Long loanId) {
		LoanVariation loanVariation = loanVariationService.getByLoanId(loanId);
		if (loanVariation == null) {
			logger.error("loanVariation null loanId" + loanId);
			return;
		}
		LoanInfo loanInfo = loanVariationService
				.getLoanInfoFromCache(loanVariation.getLoanId());

		if (loanInfo.getIsFlow() != null && loanInfo.getIsFlow() == 1) {
			flowLoanTender.doTenderExpiredBiz(loanVariation);
		} else {
			normalLoanTender.doTenderExpiredBiz(loanVariation);
		}

	}

	@RequestMapping("/findLoanExpired")
	public void testFindLoanExpired() {

		loanTimeOutTask.findTimeOutLoanSchedule();

	}

	/*
	 * @RequestMapping("/testReturn") public void testReturn(Long loanRepayId) {
	 * repayTask.nomalLoanTenderReturn(loanRepayId); }
	 */

	@RequestMapping("/testTenderAuto")
	public void testTenderAuto() {
		loanTimeOpenTask.findTimeOpenLoanSchedule();
	}

	@RequestMapping("/realTimeFinance")
	public void realTimeFinance() {
		
			realTimeFinance.doBiz();
		
	}

	@RequestMapping("/realTimeFinanceDate")
	public void realTimeFinanceDate(String dateStr) {
		try {
			financeService.getFinanceData(dateStr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping("/refreshSysConfig")
	public void refreshSysConfig() {
		sysConfigService.refresh();
	}

	@RequestMapping("/mailpdf")
	public void mailPdf(HttpServletRequest req, HttpServletResponse res) {
		Configuration configuration = this.freemarkerConfig.getConfiguration();
		// no data
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			Template pdfTmplate = configuration
					.getTemplate("user/pdf/tender_contract_pdf.ftl");
			String htmlText = FreeMarkerTemplateUtils
					.processTemplateIntoString(pdfTmplate, params);
			String path = "C:/test.pdf";
			FileOutputStream out = new FileOutputStream(new File(path));
			PdfDownload.parseXHtml(out, htmlText);
			// 邮件类型，true表示Html邮件，false表示纯文本邮件
			// EmailSender emailSender = new EmailSender(true);

			// 接收者邮箱
			String subject = "FansMail测试-Html邮件！";
			String content = "test";

			String to = "240370818@qq.com";
			List<String> list = new ArrayList<String>();
			list.add(to);
			EmailAttachment attachment = new EmailAttachment();
			attachment.setPath(path);
			// emailSender.sendEmail(list, subject,
			// content,Arrays.asList(attachment));
			SendCloudMail.send(to, subject, content);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}

	}

	@RequestMapping("/testMessage")
	public void testMessage() throws IOException {
		String msg = BizException.getGlobalMessage("tender_status_error");
		System.out.println(msg);

		/*
		 * String configPath ="config/businessException"; //String msg =
		 * ResourceBundle.getBundle(configPath2+Const.ERR_MSG,
		 * LocaleContextHolder.getLocale()).getString(key); String msg =
		 * ResourceBundle
		 * .getBundle(configPath+Const.ERR_MSG,LocaleContextHolder.
		 * getLocale()).getString("tender_status_error"); ResourceBundle.
		 * System.out.println(msg);
		 */
	}

}
